package com.cljz.makepassenger.present.activity;

import com.cljz.makepassenger.base.BaseP;
import com.cljz.makepassenger.model.net.api.Api;
import com.cljz.makepassenger.model.net.bean.SetUserInfoBean;
import com.cljz.makepassenger.ui.activity.PaySetActivity;
import com.clzj.makepassenger.bean.UserInfo;

import java.util.HashMap;

import cn.droidlover.xdroidmvp.net.ApiSubcriber;
import cn.droidlover.xdroidmvp.net.NetError;
import cn.droidlover.xdroidmvp.net.XApi;
import cn.droidlover.xdroidmvp.net.diy.Base64Utils;
import okhttp3.RequestBody;

/**
 * Created by CLJZ on 2017/6/14.
 */

public class PaySetP extends BaseP<PaySetActivity> {

    public void setAlipay(final String id, final String name){
        HashMap<String, String> map = new HashMap<>();
        map.put("token",getToken());
        map.put("alipay",id);
        map.put("user_name",name);
        String body = Base64Utils.enCode(gson.toJson(map));
        RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("text/plain;charset=UTF-8"), body);
        Api.getResponseInfoAPI().setUserInfoData(requestBody)
                .compose(XApi.<SetUserInfoBean>getApiTransformer())         //异常处理
                .compose(XApi.<SetUserInfoBean>getScheduler())              //线程切换
                .compose(getV().<SetUserInfoBean>bindToLifecycle())
                .subscribe(new ApiSubcriber<SetUserInfoBean>() {
                    @Override
                    protected void onFail(NetError error) {
                        getV().setAlipayFailed(error.getMessage());
                    }

                    @Override
                    public void onNext(SetUserInfoBean setUserInfoBean) {
                        if ("0".equals(setUserInfoBean.getError_code())) {
                            intoDB(id,name);
                            getV().setAlipaySuccess(id,name);
                        } else if ("1000".equals(setUserInfoBean.getError_code())) {
                            getV().loginOvertime(1);
                        } else {
                            getV().setAlipayFailed(setUserInfoBean.getMsg());
                        }
                    }
                });

    }

    public void intoDB(String id,String name){
        UserInfo info = getLocalUserInfo(getToken());
        info.setAlipay(id);
        info.setUser_name(name);
        updateDB(info);
    }

}
